package com.alpha.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取容器内对象
 * @author zhaojiulin
 * @date 2020/2/27 13:34
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static <T> T getBean(Class<?> cls) {
        try {
            return (T) applicationContext.getBean(cls);
        }catch (BeansException e) {
            return null;
        }
    }

    public static <T> T getBean(String beanName) {
        try {
            return (T) applicationContext.getBean(beanName);
        } catch (BeansException e) {
            return null;
        }
    }

}
